package com.zzl.finance.data.controller;

import com.alibaba.nacos.common.utils.CollectionUtils;
import com.alibaba.nacos.common.utils.IoUtils;
import com.zzl.apidoc.annotation.ApidocController;
import com.zzl.apidoc.annotation.ApidocOperation;
import com.zzl.apidoc.annotation.ApidocParam;
import com.zzl.finance.data.constant.FileBucketTypeConstant;
import com.zzl.finance.data.dto.*;
import com.zzl.finance.data.feign.FileCenterFeign;
import com.zzl.finance.data.service.EnterpriseService;
import com.zzl.finance.data.service.FileService;
import com.zzl.general.common.apidoc.annotation.ApidocResultKeyValR;
import com.zzl.general.common.apidoc.annotation.ApidocReturnR;
import com.zzl.general.common.apidoc.constants.ResultTypeInR;
import com.zzl.general.common.exception.SysException;
import com.zzl.general.common.utils.LogUtils;
import com.zzl.general.common.utils.Result;
import feign.Response;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author gull
 * @date 2021-11-09 20:04:58
 */
@ApidocController("0注册")
@RestController
@SuppressWarnings("javadoc")
@RequestMapping("data/login")
@Slf4j
public class RegisterController {
    @SuppressWarnings("all")
    @Autowired
    private EnterpriseService supplierService;
    @Autowired
    private FileService fileService;
    @Autowired
    private FileCenterFeign fileCenterFeign;

    /**
     * 电子债权供应商注册
     */
    @PostMapping("/allowAuth/voucherRegister")
    @ApidocOperation(description = "企业注册（包括核心企业、厂子和供应商）", operationId = "data/login/allowAuth/register/r1")
    @ApidocReturnR
    public Result allVoucherRegister(@ApidocParam(name = "保存的对象值", required = true) @RequestBody @Valid VoucherEnterpriseAddDto supplier) {
        log.info("供应商注册入参supplier：{}", supplier);
        if (null == supplier) {
            return Result.error("供应商参数不能为空");
        }
        try {
            supplierService.saveVoucherSupplier(supplier);
        } catch (SysException e) {
            LogUtils.logSysException(log, e);
            return Result.error(e.getMsg());
        }
        return Result.ok();
    }

    /**
     * 上传文件和唯一标识
     *
     * @param file
     * @return
     */
//    @ApidocOperation(description = "电脑上传文件", operationId = "data/login/allowAuth/uploadFile")
    @ApidocReturnR(otherkv = {
            @ApidocResultKeyValR(resultType = ResultTypeInR.TYPE_OBJECT, key = "businessInfoDto", valueClass = BusinessInfoDto.class)
    })
    @PostMapping("/allowAuth/uploadFile")
    public Result upLoadFile(@ApidocParam(name = "file", description = "文件") @NotNull MultipartFile file
            , @ApidocParam(name = "type"
            , description = "证件类型，FRONT_ID_CARD：身份证正面,BACK_ID_CARD：身份证反面，" +
            "BUSINESS_LICENSE：营业执照，LETTER_AUTHORIZATION：授权函"
            , required = true) String type) {
        BusinessInfoDto businessInfoDto = null;
        if (StringUtils.isBlank(type)) {
            return Result.error("参数不能为空");
        }
        try {
            businessInfoDto = fileService.upLoadBusinessInfoFile(file, type);
        } catch (SysException e) {
            LogUtils.logSysException(log, e);
            return Result.error(e.getMsg());
        }
        return Result.ok().put("data", businessInfoDto);
    }

    @ApidocOperation(description = "手机上传文件", operationId = "data/login/allowAuth/upLoadFileByMobile")
    @ApidocReturnR(otherkv = {
            @ApidocResultKeyValR(resultType = ResultTypeInR.TYPE_OBJECT, key = "objId", valueClass = String.class)
    })
    @PostMapping("/allowAuth/upLoadFileByMobile")
    public Result upLoadFileByMobile(@ApidocParam(name = "file", description = "文件") @NotNull MultipartFile file
            , @ApidocParam(name = "socketId", description = "用户唯一标识", required = true) String socketId
            , @ApidocParam(name = "type", description = "证件类型，" +
            "LEGAL_FRONT_ID_CARD：法人身份证正面,LEGAL_BACK_ID_CARD：法人身份证反面，ADMIN_FRONT_ID_CARD：管理员身份证正面," +
            "ADMIN_BACK_ID_CARD：管理员身份证反面，BUSINESS_LICENSE：营业执照，授权书：CERTIFICATE_AUTH",
            required = true) String type
    ) {
        if (StringUtils.isBlank(socketId)) {
            return Result.error("参数不能为空");
        }
        String objId = null;
        try {
            objId = fileService.upLoadFileByMobile(file, socketId, type);
        } catch (SysException e) {
            LogUtils.logSysException(log, e);
            return Result.error(e.getMsg());
        }
        return Result.ok().put("objId", objId);
    }


    @ApidocOperation(description = "手机提交多个文件", operationId = "data/login/allowAuth/submitFileByMobile")
    @ApidocReturnR(otherkv = {
            @ApidocResultKeyValR(resultType = ResultTypeInR.TYPE_OBJECT, key = "objId", valueClass = String.class)
    })
    @PostMapping("/allowAuth/submitFileByMobile")
    public Result submitFileByMobile(@ApidocParam(description = "手机上传参数", name = "mobileFile", required = true)
                                     @RequestBody MobileFileList fileList) {
        try {
            fileService.submitFileByMobile(fileList);
        } catch (SysException e) {
            LogUtils.logSysException(log, e);
            return Result.error(e.getMsg());
        }
        return Result.ok();
    }

    @ApidocOperation(description = " 下载文件", operationId = "/downLoadFile/objId/r1")
    @ApidocReturnR
    @GetMapping("/allowAuth/downLoadFile/{objId}/{type}")
    public void downLoadFile(HttpServletResponse response, @ApidocParam(name = "objId", description = "文件唯一标识")
    @PathVariable("objId") String objId, @ApidocParam(name = "type"
            , description = "证件类型，FRONT_ID_CARD：身份证正面,BACK_ID_CARD：身份证反面，\" +\n" +
            "            \"BUSINESS_LICENSE：营业执照，LETTER_AUTHORIZATION：授权函") @PathVariable("type") String type) {
        Response responseImg = fileCenterFeign.downloadFileMongoAllowAuth(objId, type);
        try {
            IoUtils.copy(responseImg.body().asInputStream(), response.getOutputStream());
            response.setCharacterEncoding("UTF-8");
            // 设置文件头：最后一个参数是设置下载文件名
            response.setHeader("Content-Disposition", responseImg.headers().get("Content-Disposition").stream().collect(Collectors.toList()).get(0));

        } catch (IOException e) {
            log.error("文件下载异常");
        }
    }

    @ApidocOperation(description = " 下载图片 重新定义图片大小", operationId = "/allowAuth/downLoadImageResizeNoColor")
    @ApidocReturnR
    @GetMapping("/allowAuth/downLoadImageResizeNoColor")
    public Result downLoadImageResizeNoColor(HttpServletResponse response
            , @ApidocParam(name = "objId", description = "文件唯一标识") @RequestParam("objId") String objId
            , @ApidocParam(name = "width", description = "宽") @RequestParam("width") int width
            , @ApidocParam(name = "height", description = "高") @RequestParam("height") int height
            , @ApidocParam(name = "type", description = "证件类型，ID_CARD：身份证,BUSINESS_LICENSE：营业执照") @RequestParam("type") String type) {
        Response responseImg = fileCenterFeign.downLoadImageResizeNoColor(objId, type, width, height);
        try {
            IoUtils.copy(responseImg.body().asInputStream(), response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Result.ok();
    }


    @ApidocOperation(description = " 下载文件带权限验证", operationId = "/downLoadFile/objId/r2")
    @ApidocReturnR
    @GetMapping("/allowAuth/downLoadFileAuth/{objId}/{type}")
    public void downLoadFileAuth(HttpServletResponse response, @ApidocParam(name = "objId", description = "文件唯一标识")
    @PathVariable("objId") String objId, @ApidocParam(name = "type"
            , description = "文件类型 AUTHORIZATION_LETTER：授权函") @PathVariable("type") String type) {
        fileService.downloadFile(response, type, objId, null);
    }


    /**
     * 供应商注册
     */
    @PostMapping("/allowAuth/register")
    @ApidocOperation(description = "供应商注册", operationId = "data/login/allowAuth/register")
    @ApidocReturnR
    public Result register(@ApidocParam(name = "保存的对象值", required = true) @RequestBody @Valid EnterpriseAddDto supplier) {
        log.info("供应商注册入参supplier：{}", supplier);
        if (null == supplier) {
            return Result.error("供应商参数不能为空");
        }
        if (null == supplier.getBusinessLicenseExpireTime() && !supplier.getBusinessLicenseLongTime()) {
            return Result.error("营业执照有效期不能为空");
        }
        if (null != supplier.getBusinessLicenseExpireTime() && supplier.getBusinessLicenseLongTime()) {
            return Result.error("营业执照长期有效不需要填写具体有效期");
        }
        try {
            supplierService.saveSupplier(supplier);
        } catch (SysException e) {
            LogUtils.logSysException(log, e);
            return Result.error(e.getMsg());
        }
        return Result.ok();
    }


    /**
     * 普通文件上传
     *
     * @param file 对象
     */
    @PostMapping("/allowAuth/uploadFileOrd")
    @ApidocOperation(description = "企业认证文件上传", operationId = "data/financialproduct/financial/uploadFile/a1")
    @ApidocReturnR(otherkv = {
            @ApidocResultKeyValR(resultType = ResultTypeInR.TYPE_OBJECT, key = "data", valueClass = String.class)
    })
    public Result upLoadFileOrd(@ApidocParam(name = "file", description = "文件") @NotNull MultipartFile file) {
        try {
            String objId = fileService.upLoadFile(file, FileBucketTypeConstant.FILE_ORDINARY_FILE.getKey());
            return Result.ok().data(objId);
        } catch (SysException e) {
            LogUtils.logSysException(log, e);
            return Result.error(e.getMsg());
        }
    }


    @ApidocOperation(description = " 企业认证文件下载", operationId = "/downLoadFile/objId/r4")
    @ApidocReturnR
    @GetMapping("/allowAuth/downLoadFileOrd/{objId}")
    public void allowAuthDownLoadFileOrd(HttpServletResponse response, @ApidocParam(name = "objId", description = "文件唯一标识")
    @PathVariable("objId") String objId) {
        Response responseImg = fileCenterFeign.downloadFileMongoAllowAuth(objId, FileBucketTypeConstant.FILE_ORDINARY_FILE.getKey());
        try {
            IoUtils.copy(responseImg.body().asInputStream(), response.getOutputStream());
            response.setCharacterEncoding("UTF-8");
            // 设置文件头：最后一个参数是设置下载文件名
            response.setHeader("Content-Disposition", responseImg.headers().get("Content-Disposition").stream().collect(Collectors.toList()).get(0));

        } catch (IOException e) {
            log.error("文件下载异常");
        }
    }

    @ApidocOperation(description = " 企业认证文件预览", operationId = "/previewFile/objId")
    @ApidocReturnR
    @GetMapping("/allowAuth/previewFile/{objId}")
    public void previewFile(HttpServletResponse response, @ApidocParam(name = "objId", description = "文件唯一标识")
    @PathVariable("objId") String objId) {
        Response responseImg = fileCenterFeign.previewFileNoAuth(objId, FileBucketTypeConstant.FILE_ORDINARY_FILE.getKey());
        try {
            IoUtils.copy(responseImg.body().asInputStream(), response.getOutputStream());
            response.setCharacterEncoding("UTF-8");
            // 2.设置文件头：预览设置，如果是浏览器可以识别的文件
            response.setHeader("Content-Disposition", responseImg.headers().get("Content-Disposition").stream().collect(Collectors.toList()).get(0));
        } catch (IOException e) {
            log.error("文件预览异常");
        }
    }

}
